package pkj.no.notetab.gui;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;

import javax.swing.*;

public class Tab extends JPanel {

	private TextHolder text;
	private String name;
	private Tabs tabs;
	private File belongsToFile = null;

	
	public TextHolder getTextHolder(){
		return text;
	}
	private boolean saved = false;

	public boolean isSaved(){
		return saved;
	}
	public boolean isEmpty(){
		return text.getText().equals("");
	}
	
	
	public Tab(Tabs tabs, String name) {
		text = new TextHolder(tabs, this);
		this.tabs = tabs;
		setLayout(new BorderLayout());
		this.name = name;
		add(text, BorderLayout.CENTER);

		
	}

	public void setBelongsToFile(File belongsToFile) {
		this.belongsToFile = belongsToFile;
	}

	public File getBelongsToFile() {
		return belongsToFile;
	}



	public void setName(String name) {
		this.name = name;
	}

	public Tab(Tabs tabs) {
		this(tabs, "+");
		saved = true;
	}

	public String getName() {
		return name + (saved ? "" : " *");
	}

	public JEditorPane getTextArea() {
		return text;
	}

	public void setSaved(boolean s) {
		saved = s;
	}

	protected void saveToFile(File f) throws IOException {
		PrintWriter pw;
		pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
		pw.print(this.getTextArea().getText());
		pw.close();

		setSaved(true);
		setName(f.getName());
		setBelongsToFile(f);
		tabs.refresh();
		
		this.text.requestFocus();
	}
	
	public void save() throws IOException{
		File f = getBelongsToFile();
		if (f != null){
			saveToFile(f);
		}else{
			saveAs();
		}
	}
	
	public void saveAs() throws IOException{
		final JFileChooser fc = new JFileChooser();
		int returnVal = fc.showSaveDialog(Tab.this);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File fe = fc.getSelectedFile();
			saveToFile(fe);
		}
	}
}
